import {Component, Inject, OnInit, Optional} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {ActivatedRoute, Router} from '@angular/router';
import {PostModule} from '../../../../service/post';
import {appConfig} from '../../../../service/common';
import {UtilityService} from '../../../../service/utils.service';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {EmpModule} from '../../../../service/emp';
import {PageModule} from '../../../../service/common.module';
import * as moment from 'moment';
import {CommondictServe} from '../../../../service/commonDict';
import {ReuseTabService} from '@delon/abc';

@Component({
  selector: 'app-group-post',
  templateUrl: './group-post.component.html',
})
export class GroupPostComponent implements OnInit {

    constructor(
        private http: _HttpClient,
        private router: Router,
        private activatedRoute: ActivatedRoute, // 注入路由，接收到参数,
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService,
        private commondict: CommondictServe,
        @Optional() @Inject(ReuseTabService) private reuseTabService: ReuseTabService,
    ) {}

    post: PostModule = new PostModule();
    postAdd: PostModule = new PostModule();

    ifshow: boolean = true;
    // 性别
    gender: any;
    // 岗位类型
    positionType: any;
    // 状态
    postStatus: any;
    page: any;
    postAddEdit: string; // 新增/修改 崗位
    appConfit: string; // 是否有修改按钮
    postTitle: string;
    appcofList: any;
    // blDuct 所属职务
    blDuct= [
        {key: 'practice' , value: '行长'},
        {key: 'primary' , value: '业务经理'},
        {key: 'intermediate' , value: '理财经理'},
        {key: 'Senior' , value: '营销经理'},
        {key: 'scientist' , value: '大厅经理'},
        {key: 'management' , value: '会计'},
        {key: 'Director' , value: '总管'},
    ];

    loading = false;
    expandForm = false;
    total: number;
    postGuid: string;
    orgGuid: string;

    // 岗位员工
    modalVisible = false;
    empdistribution = false;
    modelSelect: boolean; // 弹出框内容选择

    isEdit = false; // 默认是新增 不是修改
    data: any[] = []; // 表格数据
    isappcodeSlash = false; // 验证服务
    headerData = [  // 配置表头内容
        {value: '岗位名称' , key: 'positionName', isclick: false},
        {value: '上级岗位' , key: 'parentName', isclick: false},
        {value: '岗位状态' , key: 'positionStatus', isclick: false},
        {value: '在岗员工数' , key: 'empNum', isclick: true},
        {value: '岗位有效日期' , key: 'startDate', isclick: false},
        {value: '岗位失效日期' , key: 'endDate', isclick: false},
    ];


    moreData = {
        morebutton: true,
        buttons: [
            {key: 'Overview' , value: '查看概况'},
        ]
    };
    // switch控制
    parentPost = false;
    startDate = false;
    endDate = false;
   selectedRows: any; // 选择的总数

    // 表头按钮
    buttons = [
        {key: 'add', value: '新增岗位', buttonCode: appConfig.funcObject.group.delGrouppost}
    ]

    copy: any;
    pageIndex = 1; // 当前页数
    groupCode: string;
    Parentsguid: any;
    configTitle: string;
    groupGuid: string; // 工作組id
    ngOnInit() {
           this.appcofList  = appConfig;
        this.groupCode = this.activatedRoute.snapshot.params.id; // 拿到父组件传过来的组织机构的guid来进行操作
        this.getData(); // 只会触发一次，但是ngchanges并不会触发咋办
        this.queryGroup(this.groupCode);
        this.dictQueryKey();
        // 查询工作组详情
        this.utilityService.getData(appConfig.serverUrl  + appConfig.API.omGroups + '/' + this.groupCode)
            .subscribe(
                (val) => {
                    console.log(val.result)
                    this.reuseTabService.title = val.result.groupName + '下岗位'
                },
            );
        this.configTitle = '修改';
    }


    dictQueryKey() {
        this.commondict.queryDictKey(appConfig.dictKeyList.postStatus)
            .subscribe((val) => {
                this.postStatus = val.result;
            })

        this.commondict.queryDictKey(appConfig.dictKeyList.positionType)
            .subscribe((val) => {
                this.positionType = val.result;
            })

    }


    getData(option?) { // 初始化请求后台数据
        if (option) {
            this.pageIndex = 1;
        }
        this.page = {
            condition: this.objJSon, // 搜索内容
            page: {
                current: this.pageIndex,
                size: this.post.size,
            }
        };

        // 查询工作组下所有岗位
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.omGroups + '/' + this.groupCode + '/positionIn',  this.page)
            .subscribe(
                (val) => {
                    // 没有在岗员工，模拟一下
                    for ( let i = 0; i < val.result.records.length; i++) {
                        if ( val.result.records[i].positionStatus === '正常') {
                            val.result.records[i].buttonData = [ {key: 'logOut', value: '注销', if: false}, {key: 'app', value: '应用权限', if: false}];
                        } else {
                            val.result.records[i].buttonData = [ {key: 'start', value: '启用', if: false}, {key: 'dels', value: '删除', if: false}];
                        }
                        if (val.result.records[i].startDate) {
                            val.result.records[i].startDate = moment(val.result.records[i].startDate).format('YYYY-MM-DD');
                        }

                        if (val.result.records[i].endDate) {
                            val.result.records[i].endDate = moment(val.result.records[i].endDate).format('YYYY-MM-DD');
                        }
                    }
                    this.data = val.result.records;
                    this.total = val.result.total;
                });

    }



    queryGroup(groupCode) {
        this.utilityService.getData(appConfig.serverUrl  + appConfig.API.omGroups + '/' + groupCode )
            .subscribe(
                (val) => {
                    this.orgGuid = val.result.guidOrg;
                    this.groupGuid = val.result.guid;
                },
            );
    }


    // 枚举值转换
    // 岗位类型转换
    postType(event) {
        if (event.positionType === '机构岗位') {
            event.positionType = '01';
        } else if (event.positionType === '工作组岗位') {
            event.positionType = '02';
        }
    }
    // 岗位状态转换
    Statuspost(event) {
        if (event.positionStatus === '正常') {
            event.positionStatus = 'running';
        } else if (event.positionStatus === '注销') {
            event.positionStatus = 'cancel';
        }
    }


    /* 获取工作组下可分配岗位*/
    queryOrgPost(postGuid?) {
        if(postGuid) {
            let objJson = {
                positionId: postGuid,
                groupId: this.groupGuid
            }
            this.utilityService.postData(appConfig.serverUrl + appConfig.API.listsByGroupId, objJson)
                .subscribe(
                    (val) => {
                        this.Parentsguid = val.result;
                    });
        } else {
            let objJson = {
                groupId: this.groupGuid
            }
            this.utilityService.postData(appConfig.serverUrl + appConfig.API.listsByGroupId, objJson)
                .subscribe(
                    (val) => {
                        this.Parentsguid = val.result;
                    });
        }
    }

    // 想一下，能否把这三个方法封装到一个ts里面，引入即可，不然每次都写着三个方法不太现实。
    // 列表组件传过来的内容
    addHandler(event) {
        this.ifshow = false; // 默认是基础信息
        this.isappcodeSlash = false;
        this.postAdd = new PostModule(); // 重新清空赋值
        if (event === 'add') {
            this.postAddEdit = '新增岗位'
            this.queryOrgPost();
            this.postAdd.positionStatus = 'running';
            this.startDate = false; // 默认false
            this.parentPost = false; // 默认false
            this.endDate = false; // 默认false
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.postAdd.positionType = '02';
            this.isEdit = false;
        } else { // 代表修改，把修改的内容传递进去，重新渲染
            if (event.guidParents !== '') {
                this.parentPost = true;
            }
            if (event.startDate) {
                this.startDate = true;
            }
            if(event.endDate) {
                this.endDate = true;
            }
            this.postAddEdit = '修改岗位'
            this.postAdd.positionType = '02';
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.Parentsguid = [];
            this.Statuspost(event)
            this.queryOrgPost(event.guid);
            this.postType(event)
            this.postAdd = event;

            this.isEdit = true;
        }
    }


    // 验证是否重复
    AppCodeexit(postAddEdit, postCode) {
        if(postAddEdit === '新增岗位') {
            let objJson = {
                guid: '',
                positionCode: postCode,
                guidMapping: this.groupGuid
            }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.existAddPositionCode , objJson)
                .subscribe(
                    (sus) => {
                        if (sus.result) {
                            this.isappcodeSlash = true; // 重复
                        } else {
                            this.isappcodeSlash = false; // 不重复
                        }
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        } else {
            let objJson = {
                guid: this.postAdd.guid,
                positionCode: postCode,
                guidMapping: this.groupGuid
            }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.existUpdatePositionCode , objJson)
                .subscribe(
                    (sus) => {
                        if (sus.result) {
                            this.isappcodeSlash = true; // 重复
                        } else {
                            this.isappcodeSlash = false; // 不重复
                        }
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        }
    }



    buttonEvent(event) {
        if (event.names) {
            if (event.names.key === 'logOut') {
                this.utilityService.putData(appConfig.serverUrl  + appConfig.API.cancel + '/' + event.guid )
                    .subscribe(
                        (val) => {
                            console.log(val)
                            this.nznot.create('success', val.msg , val.msg);
                            this.getData();
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        }
                    );
            }

            if (event.names.key === 'app') {
                this.showAdd = true; // 没有新增
                this.postName = event.postName;
                this.postGuid = event.guid;
                this.appConfit = '';
                this.modelSelect = false; // 打开弹出框
                this.postTitle = '岗位' + event.positionName + '可以使用的应用系统'
                this.empdistribution = true; // 弹出在岗员工数代码
                this.getPostApp(); // 查询所有的应用
                this.getPostApplist(); // 查询已分配的权限

            }

            if (event.names.key === 'dels') {
                this.deleatData(event);
            }

            if (event.names.key === 'start') {
                this.utilityService.putData(appConfig.serverUrl  + appConfig.API.running + '/' + event.guid )
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            this.getData();
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        }
                    );
            }
        } else {

        }
    }


    // 列表传入的翻页数据
    monitorHandler(event) {
        this.pageIndex = event;
        this.getData();
    }

    // 接受子组件删除的数据 单条还是多条
    deleatData(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除所选岗位?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.postDel + '/' + event.guid)
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            if ( !(( this.total - 1) % 10)) {
                                // if ( !(( this.total - this.acfundata.length) % 10)) { // 支持批量删除的方法
                                this.post.pi -- ;
                                this.getData();
                            }
                            this.getData();
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
            }
        });
    }

    // 批量删除
    deleteBatch(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除这' + event.length + '条岗位吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let delarray = [];
                for( let i = 0; i < event.length; i++) {
                    delarray.push(event[i].guid);
                }
                let deletaObj = {
                    deleteList: delarray,
                    guid: this.groupGuid
                }
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.postDelte, deletaObj )
                    .subscribe(
                        (val) => {
                            this.getData();
                            this.selectedRows = []
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.getData();
                this.selectedRows = []
            }
        });
    }


    // 列表按钮方法
    buttonDataHandler(event) {
        console.log(event); // 根据event.value来判断不同的请求，来获取结果和方法或者进行路由的跳转
        if (event.value ===  'Authority') {
            console.log(event.key);
        }

        if (event.value ===  'Overview') {
            console.log(event.key);
        }

    }


    selectedRow(event) { // 选中方法，折叠层按钮显示方法

    }
    postInfo: any;
    // 处理行为代码，跳转、弹出框、其他交互
    isActive(event) {
        this.postInfo = event; // 保存岗位信息
        this.empdistribution = true; // 弹出在岗员工数代码
        this.modelSelect = true;
        this.postTitle = '岗位' + event.parentName + '下的员工'
        this.postGuid = event.guid;
        this.getEmpData(event.guid);
        this.getEmpList(event.guid);
    }


    objJSon = {};
    // 搜索框
    search() {
        this.objJSon = this.post;
        this.getData(this.post);
    }

    reset() {
        this.objJSon = {};
        this.post = new PostModule();
        this.getData();
    }
    // switch开关
    switchchange(item, status) {
        if (item === 'parentPost') {
            this.parentPost = status;
        }
        if (item === 'startDate') {
            this.startDate = status;
        }
        if (item === 'endDate') {
            this.endDate = status;
        }
    }


    canel() {
        this.modalVisible = false;
        this.getData();
    }

    // 弹出框保存组件
    save() {
        const jsonOption = this.postAdd;
        jsonOption.guidMapping = this.groupGuid;
        jsonOption.groupCode = this.groupCode;
        jsonOption.isLeaf = 'Y' ;
        jsonOption.subCount = 0 ;
        jsonOption.positionType = '02'; // 默认是工作组岗位
        if (!this.isEdit) { // 新增数据
            if (this.startDate && jsonOption.startDate === undefined) { // 如果是true 那么就默认当天
                jsonOption.startDate =  moment(new Date()).format('YYYY-MM-DD'); // 默认当前时间
            }
            if (this.endDate && jsonOption.endDate === undefined) { // 如果是true 那么就默认当天
                jsonOption.endDate =  moment(new Date()).format('YYYY-MM-DD'); // 默认当前时间
            }
            const jsonAjax = {
                groupCode: this.groupCode,
                omPositionRequest: jsonOption
            }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.groupPosition, jsonAjax)
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        } else {
            this.utilityService.putData(appConfig.serverUrl  + appConfig.API.postDel, jsonOption)
                .subscribe(
                    (val) => {
                        this.getData();
                        this.nznot.create('success', val.msg , val.msg);
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        }
        this.modalVisible = false;
    }


    // 在岗员工数代码部分
    empDataheader = [  // 配置表头内容
        {value: '员工姓名' , key: 'empName', isclick: false},
        {value: '操作员', key: 'operatorName',  isclick:  false},
        {value: '员工状态' , key: 'empstatus', isclick: false},
        {value: '电话号码' , key: 'mobileno', isclick: false},
        {value: '入职日期' , key: 'indate', isclick: false},
    ];


    EmpData = {
        morebutton: true,
        buttons: [
            {key: 'Onboarding' , value: '入职'},
            {key: 'Departure' , value: '离职'},
            {key: 'Overview' , value: '查看概况'},
            {key: 'operator' , value: '操作员修改'},
        ]
    };

    empTotal: number; // 总页数
    empData: any; // 总数据
    emp: EmpModule = new EmpModule();
    showAdd: boolean; // 是否显示新增按钮
    searchOptions: any;
    selectedOption: any;

    // 初始化信息
    getEmpData(guid) {
        this.showAdd = true; // 没有新增
        this.utilityService.getData(appConfig.serverUrl + appConfig.API.getPositionOutEmployee + '/' + this.groupCode +  '/getPositionOutEmployee/' +  guid)
            .subscribe(
                (val) => {
                    this.searchOptions = val.result; // 查询所有的员工，后期更改，应该查询不在岗位内的员工，接口没有好
                    // 没有在岗员工，模拟一下
                });
    }


    getEmpList(guid) {
        this.page = {
            condition: {
                guidOrg: this.groupCode,
                guidPosition: guid,
            },
            page: {
                current: this.emp.pi,
                size: this.emp.size,
            }
        };
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.queryByOrgPosition,  this.page)
            .subscribe(
                (val) => {
                    console.log(val.result)
                    // 没有在岗员工，模拟一下
                    for (let i = 0; i < val.result.records.length; i++) {
                        val.result.records[i].indate =  moment(val.result.records[i].indate).format('YYYY-MM-DD');
                        val.result.records[i].buttonData = [{key: 'dels', value: '删除', if: false}];
                    }
                    this.empData = val.result.records;
                    this.empTotal = val.result.total;
                },
                (error) => {
                    this.nznot.create('error', error.msg , error.msg);
                });
    }
    // 新增方法
    addEmp(e) {
        console.log(e);
    }
    // 顶部按钮事件
    buttonEmp(e) {
        console.log(e);
    }

    empsave() {
        this.empdistribution = false; // 弹出在岗员工数代码
        this.getData();
    }

    empEvent(e) {
        if (e.names) {
            if (e.names.key === 'dels') {
                this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.postDelemp + '/' + e.guid + '/' + this.postInfo.guid )
                    .subscribe(
                        (val) => {
                            this.nznot.create('success', val.msg , val.msg);
                            this.getEmpList(this.postGuid); // 重新查询列表内容
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            }
        }
    }

    // 翻页事件
    empHandler(e) {

    }
    // 删除事件
    deleatEmp(e) {

    }

    // 选中事件
    selectedemp() {

    }




    // 给岗位添加员工

    pages: PageModule = new PageModule;
    addEmpClick() {
        if (this.selectedOption) {
            const josnObj = {
                guidEmp: this.selectedOption,
                guidPosition: this.postGuid,
                ismain: 'N'
            }
            this.utilityService.postData(appConfig.serverUrl + appConfig.API.empAdd,  josnObj)
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                        this.getEmpList(this.postGuid); // 重新查询列表内容
                        this.getEmpData(this.postGuid); // 重新查询员工内容
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    });
        } else {
            this.nznot.create('error', '请最起码选择一个员工进行添加' , '请最起码选择一个员工进行添加');
        }


    }

    // 岗位应用权限内容
    searchOptionse; // 选择显示的内容
    selectedMultipleOption; // 多选的内容
    array = []; // 定义数组 用来清空
    Apptotal: number; // 应用翻页
    postName: string; // 岗位名称
    appData: any[] = []; // 表格数据
    AppheaderData = [  // 配置表头内容
        { value: '应用名称', key: 'appName', isclick: false },
        { value: '应用类型', key: 'appType', isclick: false },
        { value: '应用开通时间', key: 'openDate', isclick: false },

    ];

    // 查询所有应用（已经分配之外的除外）
    getPostApp() {
        this.utilityService.getData(appConfig.serverUrl + appConfig.API.appNoth + '/' + this.postGuid)
            .subscribe(
                (val) => {

                    this.searchOptions = val.result;

                }
            );
    }

    // 查询岗位下已经有的应用列表
    getPostApplist() {
        this.page = {
            page: {
                current: this.pages.pi,
                size: this.pages.size,
            }
        };
        // 模拟一下
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.listByPosition + '/' + this.postGuid,  this.page)
            .subscribe(
                (val) => {
                    console.log(val)
                    for (let i = 0; i < val.result.records.length; i++ ) {
                        val.result.records[i].buttonData = [{key: 'dels', value: '删除'}];
                        val.result.records[i].openDate =  moment(new Date()).format('YYYY-MM-DD'); // 默认当前时间
                    }
                    this.appData = val.result.records;
                    this.Apptotal = val.result.total;
                }
            );
    }




    // 给岗位新增应用
    postappAdd(event) {
        console.log(event)
        if(event.appList && event.appList.length > 0) {
            this.utilityService.postData(appConfig.serverUrl + appConfig.API.addByList,  event)
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.selectedMultipleOption = [];
                        // 重新查询岗位信息
                        this.getPostApplist();
                        this.getPostApp(); // 重新查询
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    });
        } else {
            this.nznot.create('error', '请必须选择一个应用',  '请必须选择一个应用');
        }

    }


    appClick() {
        console.log(this.selectedMultipleOption); // 传入后台，渲染
        const jsonObj = {
            guidList : this.selectedMultipleOption,
        };
        const addApp = {
            guidPosition: this.postGuid,
            appList  : this.selectedMultipleOption,
        }
        console.log(addApp);
        // 调用新增接口方法
        this.postappAdd(addApp)

        // 查询所有应用
        this.getPostApp();
        this.getPostApplist();
    }


    // 应用列表方法
    // 列表组件传过来的内容
    addappHandler(event) {

    }


    // 列表传入的翻页数据
    monitorappHandler(event) {
        console.log(event)
        this.pages.pi = event;
        this.page = {
            page: {
                current: event, // 页码
                size: this.pages.size, //  每页个数
            }
        };
        this.getPostApplist();
    }


    // 列表按钮方法
    buttonappDataHandler(event) {
        console.log(event); // 根据event.value来判断不同的请求，来获取结果和方法或者进行路由的跳转
    }

    selectedappRow(event) { // 选中方法，折叠层按钮显示方法
    }


    // 删除按钮
    appDel(event) {
        // 传第三表的id  event.id 即可
        this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.appDelpost + '/' + event.guid + '/' + this.postGuid )
            .subscribe(
                (val) => {
                    this.nznot.create('success', val.msg , val.msg);
                    this.getPostApp();
                    this.getPostApplist();
                },
                (error) => {
                    this.nznot.create('error', error.msg , error.msg);
                });

    }


    // 批量删除岗位下应用
    deleteBatchApp(event) {
        this.empdistribution = false;
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除这' + event.length + '条应用吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let delarray = [];
                for( let i = 0; i < event.length; i++) {
                    delarray.push(event[i].guid);
                }
                let deletaObj = {
                    deleteList: delarray,
                    guid: this.postGuid
                }
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.batchAppDelete, deletaObj )
                    .subscribe(
                        (val) => {
                            this.selectedRows = [];
                            this.empdistribution = true;
                            this.nznot.create('success', val.msg , val.msg);
                            this.getPostApp()
                            this.getPostApplist();
                        },
                        (error) => {
                            this.selectedRows = []
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.selectedRows = []
                this.getData()
            }
        });
    }


    appsave() {
        this.empdistribution = false;
    }

}
